package com.yincheng.oms.bussiness.order.service;

import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yincheng.oms.bussiness.order.Response;
import com.yincheng.oms.bussiness.order.entity.Order;
import com.yincheng.oms.bussiness.order.entity.OrderForm;
import com.yincheng.oms.bussiness.order.entity.OrderLog;
import com.yincheng.oms.bussiness.order.mapper.OrderLogMapper;
import com.yincheng.oms.bussiness.order.mapper.OrderMapper;
import com.yincheng.oms.bussiness.order.util.ValidateUtils;
import com.yincheng.oms.bussiness.util.excel.ExcelReadUtils;
import com.yincheng.oms.sso.entity.User;
import com.yincheng.oms.sso.util.UserUtils;

@Service
public class OrderService {

	@Autowired
	private OrderMapper orderMapper;
	
	@Autowired
	private OrderLogMapper orderLogMapper;
	
	private SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:SS"); 
	
	@Transactional(rollbackFor=Exception.class)
	public Response uploadBatchOrders(InputStream is, String fileName) throws Exception {
		Response response = new Response(Response.SUCCESS);
		List<List<Object>> list = null;
		try {
			list = ExcelReadUtils.getListByExcel(is, fileName);
		}catch(Exception e) {
			response.setCode(Response.SERVER_ERROR);
			response.setMessage(e.getCause().getMessage());
			response.setErrorMessage(e.getMessage());
			throw new Exception(e);
		}
		
		List<Order> orders = new ArrayList<Order>();
		List<OrderLog> logs = new ArrayList<OrderLog>();
		User user = UserUtils.getUser();
		for (int i = 0; i < list.size(); i++) {
			List<Object> row = list.get(i);
			Order order = new Order();
			String orderNo = (String) row.get(0);
			String orderSource = (String) row.get(1);
			String customerName = (String) row.get(2);
			String customerPhone = (String) row.get(3);
			String receiverName = (String) row.get(4);
			String receiverPhone = (String) row.get(5);
			String receiverAddress = (String) row.get(6);
			String orderCreateTime = (String) row.get(7);
			String orderPayTime = (String) row.get(8);
			
			String orderId = UUID.randomUUID().toString();
			order.setOrderId(orderId);
			order.setOrderLogStatus("1");
			order.setOrderNo(StringUtils.trim(orderNo));
			order.setOrderSource(StringUtils.trim(orderSource));
			order.setCustomerName(StringUtils.trim(customerName));
			order.setCustomerPhone(StringUtils.trim(customerPhone));
			order.setReceiverName(StringUtils.trim(receiverName));
			order.setReceiverPhone(StringUtils.trim(receiverPhone));
			order.setReceiverAddress(StringUtils.trim(receiverAddress));
			try {
				if(StringUtils.isEmpty(orderCreateTime))
					order.setOrderCreateTime(null);
				else
					order.setOrderCreateTime(sdf.parse(orderCreateTime));
			} catch (ParseException e) {
				e.printStackTrace();
				response.setCode(Response.SERVER_ERROR);
				response.setMessage("第"+(i+2)+"行，下单时间格式错误。");
				response.setErrorMessage(e.getMessage());
				return response;
			}
			try {
				if("未付款".equals(orderPayTime) || StringUtils.isEmpty(orderPayTime)) 
					order.setOrderPayTime(null);
				else
					order.setOrderPayTime(sdf.parse(orderPayTime));
			} catch (ParseException e) {
				e.printStackTrace();
				response.setCode(Response.SERVER_ERROR);
				response.setMessage("第"+(i+2)+"行，付款时间格式错误。");
				response.setErrorMessage(e.getMessage());
				return response;
			}
			orders.add(order);
			OrderLog log = new OrderLog();
			String logId = UUID.randomUUID().toString();
			log.setLogId(logId);
			log.setOrderId(orderId);
			log.setCreateTime(new Date());
			log.setOperaterUid(user.getUserId());
			log.setOperaterName(user.getUserName());
			String logMessage = "上传订单数据";
			log.setLogMessage(logMessage);
			logs.add(log);
		}
		Response checkOrders = ValidateUtils.checkOrders(orders);
		if(!checkOrders.getCode().equals(Response.SUCCESS)) {
			return checkOrders;
		}
		try {
			int i = orderMapper.batchInsert(orders);
			orderLogMapper.batchInsert(logs);
			response.setMessage("成功插入" + i + "条订单信息");
		} catch (DuplicateKeyException e) {
			response.setCode(Response.SERVER_ERROR);
			response.setMessage(e.getCause().getMessage());
			response.setErrorMessage(e.getMessage());
			throw new DuplicateKeyException(e.getCause().getMessage(), e.getCause());
		} catch (Exception e) {
			response.setCode(Response.SERVER_ERROR);
			response.setMessage(e.getCause().getMessage());
			response.setErrorMessage(e.getMessage());
			throw new Exception(e);
		}
		return response;
	}
	
	public OrderForm getOrderInfo(String orderId) {
		OrderForm form = new OrderForm();
		Order order = orderMapper.selectByPrimaryKey(orderId);
		List<OrderLog> orderLogs = orderLogMapper.selectByOrderId(orderId);
		form.setOrder(order);
		form.setOrderLogs(orderLogs);
		return form;
	}
	
	public Response addOrderLog(OrderLog log) {
		Response response = new Response(Response.SUCCESS);
		String logId = UUID.randomUUID().toString();
		log.setLogId(logId);
		log.setCreateTime(new Date());
		log.setOperaterUid(UserUtils.getUser().getUserId());
		log.setOperaterName(UserUtils.getUser().getUserName());
		orderLogMapper.insert(log);
		response.setMessage("保存成功");
		return response;
	}
	
	@Transactional
	public Response addOrderLog(OrderLog log, Order order) {
		Response response = new Response(Response.SUCCESS);
		String logId = UUID.randomUUID().toString();
		log.setLogId(logId);
		log.setCreateTime(new Date());
		log.setOperaterUid(UserUtils.getUser().getUserId());
		log.setOperaterName(UserUtils.getUser().getUserName());
		orderLogMapper.insert(log);
		response.setMessage("保存成功");
		
		int i = orderMapper.update(order);
		if(i !=1) {
			response.setCode(Response.SERVER_ERROR);
			response.setMessage("更新订单信息失败");
		}
		return response;
	}
	
	@Transactional(rollbackFor=Exception.class)
	public Response testTransational(List<OrderLog> logs, List<Order> orders) throws Exception {
		Response response = new Response(Response.SUCCESS);
		try {
			orderMapper.batchInsert(orders);
			orderLogMapper.batchInsert(logs);
		} catch (Exception e) {
			response.setCode(Response.SERVER_ERROR);
			response.setMessage(e.getCause().getMessage());
			response.setErrorMessage(e.getMessage());
			throw new Exception(e);
		}
		return response;
	}
}
